﻿using System;
using System.Text;
using System.Data;
using System.Data.OracleClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using GMS.Utils;
using GMS.BLL;
using GMS.Model;
using GMS.Web.CommonPage;

public partial class UserControl_UploadFiles : System.Web.UI.UserControl
{
    bool isLoad = false;
    bool isPic = true;
    private bool isInitialized = false;
    private bool isCreate = false;     //新建记录的时候不允许直接在控件中提交
    public FilesDB FilesDBModelTemplate = new FilesDB();
    FilesDBBLL fbll = new FilesDBBLL();
    List<FilesDB> lstFiles = new List<FilesDB>();
    HtmlProvider hp = new HtmlProvider();
    public bool isbigphoto = true;  //默认大图显示

    public void Page_Load(object sender, EventArgs e)
    {
        //注意用户控件的Page_Load是在主页面的Page_Load之后调用的，
        //因此在主页面的Page_Load中访问该控件的时候做好相应的初始化
        if (!IsPostBack) {
            SetViewStateData();
        } else {
            GetViewStateData();
        }
    }

    /// <summary>
    /// 设置控件参数
    /// </summary>
    /// <param name="template">需要设置如下字段：BELONGTABLE, BELONGID, CITYCODE, DEPT, FILETYPE, CREATOR</param>
    /// <param name="isPic">是否只允许上传图片</param>
    /// //withdetail用于判断控件是否和detail信息在一起，不通用。
    public void Initialize(FilesDB template, bool isPic, bool isAddNew)
    {
        template.FILENO = string.Empty;
        template.FLAG = "0";    //通过控件上传的肯定不入库
        template.TITLE = string.Empty;
        FilesDBModelTemplate = template;
        ISPIC = isPic;
        isInitialized = true;
        isCreate = isAddNew;
        backbt.Visible = false;
        if (Session["TabSysID"] != null)
        if (RoleModuleRightOper.HasAddUpdateRight((GMS.Model.User)Session["_User"], (int)Session["TabSysID"]))
        {
            mutiupload.HRef = "../UploadPageNoAuth/Default.aspx?TABLENAME=" + template.BELONGTABLE + "&BELONGID=" + template.BELONGID + "&FILETYPE=" + template.FILETYPE + "&CREATOR=" + template.CREATOR;
        }
        else {
            btnLoadFile.Enabled = false;
            mutiupload.Disabled = true;
        }
        SetViewStateData();
    }

    /// <summary>
    /// 必须先通过Initialize()修改条件，然后再通过Refresh()函数来刷新
    /// </summary>
    /// <returns></returns>
    public int Refresh()
    {
        DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
        if (isCreate == true)
            btnLoadFile.Visible = false;
        return 1;
    }

    /// <summary>
    /// 通过GridView显示记录
    /// </summary>
    /// <param name="TabName">对应数据库中的Belongtable字段</param>
    /// <param name="TabID">对应数据库中的Belongid字段</param>
    /// <returns></returns>
    protected int DisPlayFiles(string TabName, string TabID)
    {
        //try {
            if (!isInitialized)
                return 0;
            if (string.IsNullOrEmpty(TabName) || string.IsNullOrEmpty(TabID))
                return 0;
            string sql = " belongid ='" + TabID + "' and belongtable = '" + TabName + "'";
            DataTable filesDt = fbll.GetListWithoutFileContent(sql).Tables[0];
            photovalueTabName.Value = TabName;
            photovalueTabID.Value = TabID;
            if (isbigphoto) 
            {
                bigphotodiv.Visible = true;
                gvUploadedFiles.Visible = false;
                changedisplay.Text = "列表显示";
                String st = "";
                for (int i = 0; i < filesDt.Rows.Count; i++)
                {
                    string realPath =  filesDt.Rows[i]["filepath"].ToString() + filesDt.Rows[i]["uniqueno"].ToString() + "_" + filesDt.Rows[i]["filename"].ToString();
                    realPath = "../"+realPath.Substring(2,realPath.Length-2);
                    st = st + "  <a href=\"" + realPath + "\" title=\"" + filesDt.Rows[i]["filename"].ToString() + "\" class=\"thickbox\" rel=\"gallery-plants\"><img src=\"" + realPath + "\" alt=\"" + filesDt.Rows[i]["filename"].ToString() + "\" width=\"128\" height=\"128\"/></a>  ";
                }
                bigphotodiv.InnerHtml = st;
            }
            else
            {
                gvUploadedFiles.Visible = true;
                bigphotodiv.Visible = false;
                changedisplay.Text = "大图显示";
                gvUploadedFiles.DataSource = filesDt;
                gvUploadedFiles.DataKeyNames = new string[] { "AUTOID" };
                gvUploadedFiles.DataBind();
            }
            return 1;
        //} catch (Exception ex) {
        //    this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('数据载入失败');</script>");
        //    return 0;
        //}

    }
    public void Back_ServerClick(object sender, EventArgs e) 
    {
        string tableCode = Session["tablecodeforback"].ToString();
        string dataId = Session["cdtionforback"].ToString();
        string editable = Session["editableforback"].ToString();
        string scripts = "window.location.href = \"../public/CommonPageDetails.aspx?tablecode=" + tableCode + "&cdtion=" + dataId + "&editable=" + editable + "\";";
        Response.Write("<script>" + scripts + "</script>");
    }
    public bool ISLOAD
    {
        get { return isLoad; }
        set { isLoad = value; }
    }

    public bool ISPIC
    {
        get { return isPic; }
        set { isPic = value; }
    }

    /// <summary>
    /// 控件内部保存已经选择上传的文件
    /// </summary>
    protected void btnLoadFile_ServerClick(object sender, EventArgs e)
    {
        if (!isInitialized)
            return;
        UploadFilesToDB(); //传入文件夹名称，自动创建根目录下的文件夹
        SetViewStateData();
        //设计不通用，只有在这特殊场合有效
        Button bt = (Button)btnLoadFile;
        HtmlInputButton lb = (HtmlInputButton)bt.Parent.Parent.Page.FindControl("btnSubmit");
        lb.Visible = false;
        Button bt1 = (Button)btnLoadFile;
        HtmlInputButton lb1 = (HtmlInputButton)bt1.Parent.Parent.Page.FindControl("btnBack");
        lb1.Visible = false;
        backbt.Visible = true;
    }

    protected void changedisplay_ServerClick(object sender, EventArgs e)
    {
        isInitialized = true;
        if (changedisplay.Text == "列表显示")
            isbigphoto = false;
        DisPlayFiles(photovalueTabName.Value, photovalueTabID.Value);
        SetViewStateData();
        Button bt = (Button)btnLoadFile;
        HtmlInputButton lb = (HtmlInputButton)bt.Parent.Parent.Page.FindControl("btnSubmit");
        lb.Visible = false;
        Button bt1 = (Button)btnLoadFile;
        HtmlInputButton lb1 = (HtmlInputButton)bt1.Parent.Parent.Page.FindControl("btnBack");
        lb1.Visible = false;
        backbt.Visible = true;
    }

    /// <summary>
    /// 外部通过调用该函数来保存已经选择上传的文件
    /// </summary>
    /// <param name="citycode">整体提交时选择CityCode，将数据中所有属于{belongtab, belongid}的记录的CityCode都改成该值</param>
    public void SaveFiles(string citycode)
    {
        //修改已有记录
        try {
            if (!isInitialized)
                return;
            if (citycode != null) {
                citycode = citycode.ToUpper();
            }
            string sql = " belongid ='" + FilesDBModelTemplate.BELONGID + "' and belongtable = '" + FilesDBModelTemplate.BELONGTABLE + "'";
            List<FilesDB> filesList = fbll.GetModelListWithoutFileContent(sql);
            foreach (FilesDB fmodel in filesList) {
                if (string.IsNullOrEmpty(fmodel.CITYCODE) || fmodel.CITYCODE.ToUpper() != citycode) {
                    fmodel.CITYCODE = citycode;
                    fbll.UpdateWithoutFileContent(FilesDBModelTemplate);
                }
            }

            //保存新增文件
            FilesDBModelTemplate.CITYCODE = citycode;
            UploadFilesToDB(); //传入文件夹名称，自动创建根目录下的文件夹
            SetViewStateData();
        } catch (Exception ex) {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('上传文件失败');</script>");
        }
    }

    /// <summary>
    /// 保存文件实现
    /// </summary>
    /// <returns></returns>
    private int UploadFilesToDB()
    {
        try
        {
            //int iPos = 0;
            int iSuccess = 0;
            //int iIndex = Convert.ToInt16(txtTRLastIndex.Value.ToString());

            //根据blongtab生成文件保存目录
            string cleanTabCode = string.Empty;
            if (!string.IsNullOrEmpty(FilesDBModelTemplate.BELONGTABLE)) {
                cleanTabCode = FilesDBModelTemplate.BELONGTABLE.ToUpper();
                if (cleanTabCode.StartsWith("TAB_"))
                    cleanTabCode = cleanTabCode.Substring("TAB_".Length);
            }
            string serverVirtualDir = @"~/UploadFiles/" + cleanTabCode + "/";
            string serverPhysicalDir = Server.MapPath(serverVirtualDir);
            if (!Directory.Exists(serverPhysicalDir)) {
                Directory.CreateDirectory(serverPhysicalDir);
            }


            //检查上传文件格式是否正确
            HttpFileCollection filesCollection = Request.Files;
            List<HttpPostedFile> validFileList = new List<HttpPostedFile>();
            for (int i = 0; i < filesCollection.Count; ++i) {
                string fullname = System.IO.Path.GetFileName(filesCollection[i].FileName.ToString());
                if (string.IsNullOrEmpty(fullname) || fullname.Trim() == string.Empty)
                    continue;
                string typ2 = fullname.Substring(fullname.LastIndexOf(".") + 1);
                if (!isValid(typ2, isPic)) {
                    validFileList.Clear();
                    throw new ArgumentException("文件格式不正确，只允许上传图片");
                }
                validFileList.Add(filesCollection[i]);
               
            }


            //处理文件，每个文件建立一个Model，添加到lstFiles，然后一次性提交给数据库
            lstFiles.Clear();
            for (int i = 0; i < validFileList.Count; ++i) {
                //调用控件时，由外部程序填写FilesDB的: belongtab, belongid, filetype, flag, dept, title, fileno, citycode, creator
                //复制一个，用于插入到数据库
                FilesDB file = FilesDBModelTemplate.Clone();
                HttpPostedFile curFile = validFileList[i];
                string fullname = System.IO.Path.GetFileName(curFile.FileName);
                file.UNIQUENO = StringHelper.UniqueString();
                string fn = file.UNIQUENO + "_" + fullname; //处理上传文件重名，将UniqueString添加到文件名前面，用"_"分隔
                string strPath = serverPhysicalDir + fn;
                Stream fs = null;

                curFile.SaveAs(strPath);           //将文件保存在跟目录的UP文件夹下
                fs = curFile.InputStream;
                byte[] imageb = new byte[fs.Length];
                fs.Read(imageb, 0, imageb.Length);

                //填写剩余的字段
                file.CREATEDT = System.DateTime.Now;
                file.FILECONTENT = imageb;
                file.FILENAME = fullname;
                string extension = System.IO.Path.GetExtension(file.FILENAME);
                if (!string.IsNullOrEmpty(extension) && extension.StartsWith(".")) {
                    file.FILESUFFIX = extension.Substring(1);
                } else {
                    file.FILESUFFIX = string.Empty;
                }

                file.FILEPATH = serverVirtualDir;
                file.UPDATOR = string.Empty;
                file.UPDATEDT = null;
                file.ATTRIBUTE1 = string.Empty;
                file.ATTRIBUTE2 = string.Empty;

                lstFiles.Add(file);
            }

             iSuccess = fbll.AddFilsDB(lstFiles, FilesDBModelTemplate.BELONGID);
            if (iSuccess == 0) {
                validFileList.Clear();
                lstFiles.Clear();
                //throw new ArgumentException("上传文件失败");
            }
            validFileList.Clear();
            lstFiles.Clear();
            if (changedisplay.Text == "大图显示")
                isbigphoto = false;
            DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
        } catch (ArgumentException ae) {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('" + ae.Message + "');</script>");
            return 0;
        } catch (Exception ex) {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('上传文件失败');</script>");
            return 0;
        }
        return 1;
    }

    /// <summary>
    /// RowCommand事件处理函数，现在可处理"DeleteFile"和"DownloadFile"事件，注意都是针对本行的文件
    /// 增加了复制图片到设备表
    /// </summary>
    protected void gvUploadedFiles_RowCommand(object sender, CommandEventArgs e)
    {
        try {
            if (!isInitialized)
                return;
            //alert(e.CommandName);
            //alert(e.CommandArgument.ToString());
            int rownum = int.Parse(e.CommandArgument.ToString());
            string autoid = gvUploadedFiles.DataKeys[rownum]["AUTOID"].ToString();
            //alert(rownum.ToString ());
            bool allReadOnly = false;
            bool delupdate = false; 
            if (Session["TabSysID"] != null)
            if (!RoleModuleRightOper.HasUpdateRight((GMS.Model.User)Session["_User"], (int)Session["TabSysID"]))
                allReadOnly = true;
            if (Session["TabSysID"] != null)
                if (RoleModuleRightOper.HasDelUpdateRight((GMS.Model.User)Session["_User"], (int)Session["TabSysID"]))
                    delupdate = true;

            //删除文件
            if (e.CommandName == "DeleteFile") {
                if (delupdate)
              {
                FilesDB fmodel = fbll.GetModelWithoutFileContent(autoid);
                if (fmodel == null) {
                    DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
                    throw new ArgumentException("文件已不存在");
                }
                string fileVirtualPath = fmodel.FILEPATH + fmodel.UNIQUENO + "_" + fmodel.FILENAME;
                string filePhysicalPath = Server.MapPath(fileVirtualPath);
                if (File.Exists(filePhysicalPath)) {
                    File.Delete(filePhysicalPath);
                }
                fbll.Delete(autoid);
                if (changedisplay.Text == "大图显示")
                    isbigphoto = false;
                DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
                }else{
                    throw new ArgumentException("您没有这项权限，不能进行这项操作！");
                }

            } else if (e.CommandName == "DownloadFile") { //下载文件
                FilesDB fmodel = fbll.GetModelWithoutFileContent(autoid);
                if (fmodel == null) {
                    DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
                    throw new ArgumentException("文件已不存在");
                }

                string fileVirtualPath = fmodel.FILEPATH + fmodel.UNIQUENO + "_" + fmodel.FILENAME;
                string filePhysicalPath = Server.MapPath(fileVirtualPath);
                byte[] data = null;

                if (File.Exists(filePhysicalPath)) {
                    FileStream fs = File.Open(filePhysicalPath, FileMode.Open);
                    if (fs != null) {
                        data = new byte[fs.Length];
                        fs.Read(data, 0, data.Length);
                        fs.Close();
                    }
                } else {
                    FilesDB fmodelWithData = fbll.GetModel(autoid);
                    if (fmodelWithData != null) {
                        data = fmodelWithData.FILECONTENT;
                    }
                }

                if (data != null) {
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fmodel.FILENAME, System.Text.Encoding.GetEncoding("UTF-8")) + ";");
                    Response.ContentType = "application/octet-stream";
                    Response.BinaryWrite(data);
                    Response.Flush();
                    Response.End();
                } else {
                    throw new ArgumentException("文件读取失败");
                }
            }
            else if (e.CommandName == "TransFile") {
                if (!"TAB_TOWER".Equals(Session["tablecodeforback"].ToString().Trim()))
                {
                    throw new ArgumentException("不是杆塔表，不能进行这项操作！");
                }
                if (!allReadOnly)
                {
                FilesDB fmodel = fbll.GetModelWithoutFileContent(autoid);
                if (fmodel == null)
                {
                    DisPlayFiles(FilesDBModelTemplate.BELONGTABLE, FilesDBModelTemplate.BELONGID);
                    throw new ArgumentException("文件已不存在");
                }
                string fileVirtualPath = fmodel.FILEPATH + fmodel.UNIQUENO + "_" + fmodel.FILENAME;
                string filePhysicalPath = Server.MapPath(fileVirtualPath);
                String url = "../public/choosetarget/ChooseTarget.aspx?"+"SOURCENAME=" + fmodel.BELONGTABLE + "&SOURCEID=" 
                    + fmodel.BELONGID + "&FILENAME=" + fmodel.FILENAME + "&FILEPATH=" + fmodel.FILEPATH + "&FILESUFFIX=" 
                    + fmodel.FILESUFFIX + "&UNIQUENO=" + fmodel.UNIQUENO + "&FLAG=" + fmodel.FLAG;
                this.Page.Response.Redirect(url);
                }else{
                    throw new ArgumentException("您没有这项权限，不能进行这项操作！");
                }
            }
            SetViewStateData();
        }
        catch (ArgumentException ae)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('" + ae.Message + "');</script>");
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('页面载入出错');</script>");
            //Label1.Text = ex.StackTrace;
        }
    }

    /// <summary>
    /// 辅助函数，在客户端弹出提示框
    /// </summary>
    /// <param name="msg"></param>
    protected void alert(string msg)
    {
        this.Page.RegisterClientScriptBlock(StringHelper.UniqueString(), "<script>alert('" + msg + "');</script>");
    }


    //public void btnDel_ServerClick(object sender, EventArgs e)
    //{
    //    try {
    //        int startIndex = 0;
    //        int endIndex = 0;
    //        string strId = txtTRDelIndex.Value.ToString();
    //        GetViewStateData();
    //        if (strId != string.Empty) {
    //            string sFileID = txtDelFileID.Value.ToString();
    //            if ((sFileID != null) && (sFileID != string.Empty)) {
    //                fbll.Delete(sFileID);
    //            } else {
    //                startIndex = strSelectIndex.IndexOf(strId);
    //                strSelectIndex = strSelectIndex.Substring(0, startIndex) +
    //                    strSelectIndex.Substring(startIndex + strId.Length + 1, strSelectIndex.Length - startIndex - strId.Length - 1);
    //                ViewState["strSelectIndex"] = strSelectIndex;
    //            }
    //            string strHtml = tbfiles.InnerHtml;
    //            startIndex = strHtml.IndexOf(strId);
    //            string startHtml = strHtml.Substring(0, startIndex);
    //            string endHtml = strHtml.Substring(startIndex, strHtml.Length - startIndex);
    //            startIndex = startHtml.LastIndexOf("<tr");
    //            endIndex = endHtml.IndexOf("</tr>");
    //            strHtml = startHtml.Substring(0, startIndex) + endHtml.Substring(endIndex + 5, endHtml.Length - endIndex - 5);
    //            tbfiles.InnerHtml = strHtml;
    //            txtTRDelIndex.Value = string.Empty;
    //        }
    //    } catch (Exception) {
    //        //throw;
    //    }
    //}

    //获取回发时存在ViewState里面数据
    public void GetViewStateData()
    {
        FilesDBModelTemplate = (FilesDB)ViewState["FilesDB"];
        ISLOAD = (bool)ViewState["IsLoad"];
        ISPIC = (bool)ViewState["IsPic"];
        isCreate = (bool)ViewState["IsCreate"];
        isInitialized = (bool)ViewState["IsInitialized"];
    }

    public void SetViewStateData()
    {
        ViewState["FilesDB"] = FilesDBModelTemplate;
        ViewState["IsLoad"] = ISLOAD;
        ViewState["IsPic"] = ISPIC;
        ViewState["IsCreate"] = isCreate;
        ViewState["IsInitialized"] = isInitialized;
    }

    /// <summary>
    /// 判断上传文件后缀名
    /// </summary>
    /// <param name="strType"></param>
    /// <returns></returns>
    public bool isValid(string strType, bool isPic)
    {
        if (!isPic)
            return true;
        if (strType != null)
            strType = strType.ToUpper();
        if (strType == "GIF" || strType == "JPG" || strType == "BMP" || strType == "PNG") {
            return true;
        }
        return false;
    }

}
//=========================================================================

//using System;
//using System.Data;
//using System.Configuration;
//using System.Collections;
//using System.Web;
//using System.Web.Security;
//using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
//using System.Web.UI.HtmlControls;
//using System.Collections.Generic;
//using System.IO;
//using DL.GSTAPlan.Utils;
//using DL.GSTAPlan.BLL;
//using DL.GSTAPlan.Model;
//using DL.Web.CommonPage;

//public partial class UserControl_UploadFiles : System.Web.UI.UserControl
//{
//    bool isLoad = false;
//    bool isPic = true;
//    string strSelectIndex = string.Empty;
//    public string documentpath = string.Empty;
//    public string filename = string.Empty;
//    public FilesDB file = new FilesDB();
//    FilesDBBLL fbll = new FilesDBBLL();
//    List<FilesDB> lstFiles = new List<FilesDB>();
//    HtmlProvider hp = new HtmlProvider();
//    public List<string> lsFilesSelect = new List<string>();
//    ManageControls MC = new ManageControls();
//    ComDataOperate CDO = new ComDataOperate();

//    protected void Page_Load(object sender, EventArgs e)
//    {
//        filename = fLoadFile.FileName.ToString();
//        btnLoadFile.Attributes.Add("onclick", "AddSignRow('UpFiles')");
//    }

//    public int SaveAs(string sPath)
//    {
//        FileUpload ldFile = new FileUpload();
//        fLoadFile.SaveAs(sPath);
//        return 1;
//    }

//    public int GetTabFiles(string TabID, string TabName)
//    {
//        GetViewStateData();
//        DisPlayFiles(TabID, TabName);
//        SetViewStateData(this.file);
//        return 1;
//    }

//    public int DisPlayFiles(string TabID, string TabName)
//    {
//        string sql = " belongid ='" + TabID + "' and belongtable = '" + TabName + "'";
//        DataTable filesDt = fbll.GetListWithoutFileContent(sql).Tables[0];
//        documentpath = (string)ViewState["documentpath"];
//        tbfiles.InnerHtml = "";
//        if (filesDt.Rows.Count > 0)
//            txtTRLastIndex.Value = (filesDt.Rows.Count + 1).ToString();
//        for (int i = 0; i < filesDt.Rows.Count; ++i) {
//            DataRow dr = filesDt.Rows[i];
//            string appDir = HttpContext.Current.Request.ApplicationPath;
//            string fileDir = appDir + "/" + dr["FILEPATH"].ToString().Substring("~/".Length);
//            string sFilePath = fileDir + dr["UNIQUENO"].ToString() + "_" + dr["FILENAME"].ToString();
//            tbfiles.InnerHtml += hp.DisPlayFilesPath((int)EnumHelper.E_ColDataType.COL_IMAGE, i + 1, true, dr["AUTOID"].ToString(), dr["FILENAME"].ToString(), sFilePath);
//        }
//        return 1;
//    }

//    public bool ISLOAD
//    {
//        get { return isLoad; }
//        set { isLoad = value; }
//    }

//    public bool ISPIC
//    {
//        get { return isPic; }
//        set { isPic = value; }
//    }

//    protected void btnLoadFile_ServerClick(object sender, EventArgs e)
//    {
//        GetViewStateData();
//        UploadFilesToDB(this.documentpath); //传入文件夹名称，自动创建根目录下的文件夹


//        UploadFilesToDB()已经将文件上传到数据库了
//        if (isLoad) {
//            LoadFilesToDB("0", "", "");
//            lstFiles.Clear();
//        }
//        SetViewStateData(this.file);
//    }

//    public string LoadFilesToDB(string strID, string tabCode, string sCityCode)
//    {
//        int iSuccess = 0;
//        GetViewStateData();
//        for (int i = 0; i < lstFiles.Count; ++i) {
//            FilesDB fd = (FilesDB)lstFiles[i];
//            fd.CITYCODE = sCityCode;
//            if (strSelectIndex.IndexOf("," + fd.ATTRIBUTE1 + ",") < 0) {
//                lstFiles.RemoveAt(i);
//                --i;
//                continue;
//            }
//            if ((strID != null) && (strID != "-1") && (strID != "")) {
//                fd.BELONGID = strID;
//            } else if (fd.BELONGID != "0") {
//                strID = fd.BELONGID;
//            }
//        }
//        if (lstFiles.Count > 0) {
//            iSuccess = fbll.AddFilsDB(lstFiles, strID);
//        }
//        if (iSuccess > 0) {
//            return strID;
//        } else {
//            return "-1";
//        }

//    }

//    public int UploadFilesToDB(string serverVirtualDir)
//    {
//        try {
//            GetViewStateData();
//            int iPos = 0;
//            int iSuccess = 0;
//            int iIndex = Convert.ToInt16(txtTRLastIndex.Value.ToString());
//            string fullname = fLoadFile.FileName.ToString();
//            string fn = file.UNIQUENO + "_" + fLoadFile.FileName;
//            string typ2 = fullname.Substring(fullname.LastIndexOf(".") + 1);
//            string serverPhysicalDir = Server.MapPath(serverVirtualDir);
//            string strPath = "";
//            FileStream fs = null;
//            判断文件夹是否存在，不存在则自动创建
//            if (Directory.Exists(serverPhysicalDir) == false)//如果不存在就创建file文件夹
//            {
//                Directory.CreateDirectory(serverPhysicalDir);
//            }

//            string size = upFiles.PostedFile.ContentLength.ToString();
//            if (isValid(typ2, isPic)) {
//                fLoadFile.SaveAs(serverPhysicalDir + fn);           //将文件保存在跟目录的UP文件夹下
//                Label1.Text = (fn);
//                Image1.ImageUrl = (Server.MapPath("up") + "\\" + fn);
//                strPath = serverPhysicalDir + fn;
//                strPath = serverPhysicalDir.Substring(iPos, serverPhysicalDir.Length-iPos) + "\\" + fn;

//                fs = File.OpenRead(strPath);
//                byte[] imageb = new byte[fs.Length];
//                fs.Read(imageb, 0, imageb.Length);

//                填写剩余的字段
//                file.CREATEDT = System.DateTime.Now;
//                file.FILECONTENT = imageb;
//                file.FILENAME = fLoadFile.FileName.ToString();
//                string extension = System.IO.Path.GetExtension(file.FILENAME);
//                if (!string.IsNullOrEmpty(extension) && extension.StartsWith(".")) {
//                    file.FILESUFFIX = extension.Substring(1);
//                } else {
//                    file.FILESUFFIX = string.Empty;
//                }

//                file.FILEPATH = serverVirtualDir;
//                file.FILESUFFIX = typ2;
//                file.UPDATOR = "";
//                file.UPDATEDT = DateTime.Now;
//                file.ATTRIBUTE1 = "SignItem" + iIndex.ToString();
//                file.ATTRIBUTE2 = "";

//                lstFiles.Add(file);
//                strSelectIndex += "SignItem" + iIndex.ToString() + ",";
//                lsFilesSelect.Add("SignItem" + iIndex.ToString());
//                ViewState["lstFiles"] = lstFiles;
//                ViewState["strSelectIndex"] = strSelectIndex;
//                iSuccess = fbll.AddFilsDB(lstFiles, file.BELONGID);

//                if (iSuccess != 0) {
//                    DisPlayFiles(file.BELONGID, file.BELONGTABLE);
//                } else {
//                    this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('上传文件失败');</script>");
//                    return 0;
//                }
//            } else {
//                this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('上传文件格式不对');</script>");
//                return 0;
//            }
//        } catch (Exception) {
//            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('上传文件失败');</script>");
//            return 0;
//            throw;
//        }
//        return 1;
//    }
//    protected void btnDel_ServerClick(object sender, EventArgs e)
//    {
//        try {
//            int startIndex = 0;
//            int endIndex = 0;
//            string strId = txtTRDelIndex.Value.ToString();
//            GetViewStateData();
//            if (strId != "") {
//                string sFileID = txtDelFileID.Value.ToString();
//                if ((sFileID != null) && (sFileID != "")) {
//                    fbll.Delete(sFileID);
//                } else {
//                    startIndex = strSelectIndex.IndexOf(strId);
//                    strSelectIndex = strSelectIndex.Substring(0, startIndex) +
//                        strSelectIndex.Substring(startIndex + strId.Length + 1, strSelectIndex.Length - startIndex - strId.Length - 1);
//                    ViewState["strSelectIndex"] = strSelectIndex;
//                }
//                string strHtml = tbfiles.InnerHtml;
//                startIndex = strHtml.IndexOf(strId);
//                string startHtml = strHtml.Substring(0, startIndex);
//                string endHtml = strHtml.Substring(startIndex, strHtml.Length - startIndex);
//                startIndex = startHtml.LastIndexOf("<tr");
//                endIndex = endHtml.IndexOf("</tr>");
//                strHtml = startHtml.Substring(0, startIndex) + endHtml.Substring(endIndex + 5, endHtml.Length - endIndex - 5);
//                tbfiles.InnerHtml = strHtml;
//                txtTRDelIndex.Value = "";
//            }
//        } catch (Exception) {
//            throw;
//        }
//    }

//    获取回发时存在ViewState里面数据
//    protected void GetViewStateData()
//    {
//        file = (FilesDB)ViewState["FilesDB"];
//        lstFiles = (List<FilesDB>)ViewState["lstFiles"];
//        strSelectIndex = (string)ViewState["strSelectIndex"];
//        documentpath = (string)ViewState["documentpath"];
//        ISLOAD = (bool)ViewState["IsLoad"];
//        ISPIC = (bool)ViewState["IsPic"];
//    }

//    public void SetViewStateData(FilesDB filesdb)
//    {
//        ViewState["FilesDB"] = filesdb;
//        ViewState["IsLoad"] = ISLOAD;
//        ViewState["IsPic"] = ISPIC;
//        lstFiles.Clear();
//        strSelectIndex = ",";
//        ViewState["lstFiles"] = lstFiles;
//        ViewState["strSelectIndex"] = strSelectIndex;
//        ViewState["documentpath"] = documentpath;
//    }

//     <summary>
//     判断上传文件后缀名
//     </summary>
//     <param name="strType"></param>
//     <returns></returns>
//    public bool isValid(string strType, bool isPic)
//    {
//        if (!isPic)
//            return true;
//        if (strType != null)
//            strType = strType.ToUpper();
//        if (strType == "GIF" || strType == "JPG" || strType == "BMP" || strType == "PNG") {
//            return true;
//        }
//        return false;
//    }

//}



